package com.morehair.typehandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Author raohui
 * @Date 2021/6/7 19:01
 */
//@MappedTypes(List.class)
//@MappedJdbcTypes(JdbcType.VARCHAR)
public class ListStringTypeHandler implements TypeHandler<List<String>> {

    ObjectMapper objectMapper = new ObjectMapper();

    //输入映射List<string>---string
    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int index, List<String> strings, JdbcType jdbcType) throws SQLException {
        String value = objectMapper.writeValueAsString(strings);
        preparedStatement.setString(index, value);
    }

    //输出映射 string ----List<string>
    @Override
    public List<String> getResult(ResultSet resultSet, String columnName) throws SQLException {
        String result = resultSet.getString(columnName);
        return transfer(result);
    }

    @Override
    public List<String> getResult(ResultSet resultSet, int index) throws SQLException {
        String result = resultSet.getString(index);
        return transfer(result);
    }

    @Override
    public List<String> getResult(CallableStatement callableStatement, int index) throws SQLException {
        String result = callableStatement.getString(index);
        return transfer(result);
    }


    @SneakyThrows
    private List<String> transfer(String result) {
        if (result == null ||"".equals(result)){
            return  new ArrayList<String>();
        }
        List<String> strings = objectMapper.readValue(result, List.class);
        return strings;
    }
}
